package JUC.第02章_Future;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;


/**
 * Stream自己不会存储
 * Stream  流式计算 延迟执行
 * 集合讲的是数据   流讲的是计算
 *
 * ForkJoinPool
 * ForkJoinTask
 */
public class C1_ForkJoinPool {
    public static void main(String[] args) {
        MyTask myTask = new MyTask(0, 100);

        ForkJoinPool forkJoinPool = new ForkJoinPool();//分支合并池子  也是一种线程池
        ForkJoinTask<Integer> forkJoinTask = forkJoinPool.submit(myTask);

        System.out.println(forkJoinTask.join());
        forkJoinPool.shutdown();//关闭池子
    }
}

class MyTask extends RecursiveTask<Integer> {

    public static final Integer ADJUST_VALUE = 10;
    private int begin;
    private int end;
    private int result;

    public MyTask(int begin, int end) {
        this.begin = begin;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        if (end - begin <= ADJUST_VALUE) {
            for (int i = begin; i <= end; i++) {
                result += i;
            }
        } else {
            int middle = (end + begin) / 2;
            MyTask task01 = new MyTask(begin, middle);
            MyTask task02 = new MyTask(middle + 1, end);
            task01.fork();
            task02.fork();
            result = task01.join() + task02.join();
        }
        return result;
    }
}//把大问题   分割成一堆小问题
